package cn.mall.base.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 * 为异步任务和定时任务提供线程池支持
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    
    /**
     * 微博数据采集线程池
     * 用于处理微博数据相关的异步任务
     */
    @Bean("weiboDataTaskExecutor")
    public Executor weiboDataTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：核心数+1，可根据服务器情况调整
        executor.setCorePoolSize(10);
        // 最大线程数：CPU核心数*2，可根据服务器情况调整
        executor.setMaxPoolSize(20);
        // 队列容量：默认使用LinkedBlockingQueue
        executor.setQueueCapacity(200);
        // 线程名前缀：便于排查问题
        executor.setThreadNamePrefix("weibo-data-collector-");
        // 拒绝策略：由调用者所在线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程池关闭的超时时间
        executor.setAwaitTerminationSeconds(60);
        // 初始化
        executor.initialize();
        return executor;
    }
    
    /**
     * 默认异步任务线程池
     * 用于通用异步任务处理
     */
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(10);
        // 队列容量
        executor.setQueueCapacity(100);
        // 线程名前缀
        executor.setThreadNamePrefix("task-executor-");
        // 拒绝策略：由调用者所在线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 初始化
        executor.initialize();
        return executor;
    }
}
